<?php

/**
 * This file is part of Webman AI.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 */

namespace plugin\ai\app\handler\driver;

use plugin\ai\app\event\data\ModelRequestData;
use plugin\ai\app\event\data\ModelResponseData;
use Webman\Event\Event;
use Webman\Openai\Image;

class Dalle extends Image
{

    /**
     * @param array $data
     * @param array $options
     * @return void
     */
    public function completions(array $data, array $options)
    {
        $messages = $data['messages'] ?? [];
        $prompt = last($messages)['content'] ?? '';
        $model = $data['model'] ?? 'dall-e-3';

        $modelRequestData = new ModelRequestData();
        $modelRequestData->data = [
            'model' => $model,
            'prompt' => $prompt,
            'n' => 1,
            'size' => '1024x1024',
        ];

        $modelRequestData->options = [
            'complete' => function ($json, $response) use ($model, $modelRequestData, $options) {
                $responseData = new ModelResponseData();
                $responseData->data = $json;
                $responseData->modelRequestData = $modelRequestData;
                Event::dispatch('ai.image.generations.response', $responseData);
                $result = $responseData->data;
                $url = $result['data'][0]['url'] ?? '';
                $streamResult = $url ? ["content"=>"![]($url)"] : $result;
                $completeCallback = $options['complete'] ?? null;
                $streamCallback = $options['stream'] ?? null;
                if ($streamCallback && !isset($result['error'])) {
                    $streamCallback($streamResult, $response);
                }
                if ($completeCallback) {
                    $completeCallback($result, $response);
                }
            }
        ];
        Event::dispatch('ai.image.generations.request', $modelRequestData);
        \plugin\ai\api\Image::generations($modelRequestData->data,$modelRequestData->options);
    }

}